package com.xb.loan.util.log;

import com.xb.loan.util.ReflectionUtils;
import com.xb.loan.util.StringUtils;
import org.slf4j.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.text.MessageFormat;

/**
 * 
 * 自定义logger，通过动态代理调用目标logback logger
 */
public class DefaultLogger implements InvocationHandler {

	private Logger logger;

	public DefaultLogger(Logger logger) {
		this.logger = logger;
	}

	public Logger getLogger() {
		return logger;
	}

	public void setLogger(Logger logger) {
		this.logger = logger;
	}

	private String rtp(String format, Object[] objs) {
		return MessageFormat.format(format, objs);
	}

	private String getFormatStr(Object[] params) {
		return rtp((String) params[0], (Object[]) params[1]);
	}

	public Object invoke(Object arg0, Method method, Object[] params) throws Throwable {
		String methodName = method.getName();
		if (params.length >= 2 &&( params[1] instanceof Object[]|| params[1] instanceof LogSerializable)) {
            if (params[1] instanceof LogSerializable) {
                String[] keys = paserTemplate((String) params[0]);
                String[] values = getParamValues(params, keys);
                params[1] = values;
            }
		    if ("debug".equals(methodName)) {
				logger.debug(getFormatStr(params));
			} else if ("info".equals(methodName)) {
				logger.info(getFormatStr(params));
			} else {
				method.invoke(logger, params);
			}
		}
		else {
			method.invoke(logger, params);
		}
		return null;
	}

    private String[] getParamValues(Object[] params, String[] keys) {
        String[] values = new String[keys.length];
        for (int i = 0; i < keys.length; i++) {
            if ("".equals(keys[i].trim())) continue;
            try {
                values[i] = (String) ReflectionUtils.getFieldValue(params[1], keys[i].trim());
            } catch (Exception e) {
            }
        }
        return values;
    }
	
    private  String[] paserTemplate(String formatTemplate) {
        formatTemplate = formatTemplate.replaceAll("\\{.\\}", "");
        return StringUtils.paser(formatTemplate, "=");
    }
	
}
